<template>
    <div class="users">
        <myx-table
                
                   @addData="addUser"
                   :data="data"
                   :column="column"
                   :total="pageTotal"
                   :pageSize="pageSize"
                   :show-selection="true"
                   @current-change='currentChange'
                   searchField="username"
                   :searchMethod="searchMethod"
                   :titleList="titleList"
                   :currentPage="currentPage">
            <template #tableCell="{ scope }">
                <div v-if="scope.column.key == 'action'">
                    <el-button type="primary" plain @click="openEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" plain @click="deleteUser(scope.row)">删除</el-button>
                    <el-button type="primary" @click="assignmentRole(scope.row)">分配角色</el-button>
                </div>
                <div v-if="scope.column.key === 'sex'">
                    <b>
                        {{ scope.row.sex == 0 ? '女' : '男' }}
                    </b>
                </div>
                <div v-if="scope.column.key === 'roleName'">
                    <el-tag v-if="scope.row.roleid == 1"
                            style="background:var(--gold-bg);color:#000;padding:1.2em 2em;font-weight:bold">
                        {{ scope.row.roleName }}
                    </el-tag>
                    <el-tag
                            v-else
                            size:="large"
                            class="mx-1"
                            effect="dark"
                            round>
                        {{ scope.row.roleName }}
                    </el-tag>
                </div>
                <div v-if="scope.column.key == 'username'">
                    <el-tag
                            size:="large"
                            class="mx-2"
                            type="success"
                            effect="dark"
                            round>
                        {{ scope.row.username }}
                    </el-tag>
                </div>
                <div v-if="scope.column.key == 'nickname'">
                    <el-tag
                            size:="large"
                            class="mx-2"
                            type="info"
                            effect="dark"
                            round>
                        {{ scope.row.nickname }}
                    </el-tag>
                </div>

                <div v-if="scope.column.key == 'create_at'">
                    <el-tag
                            size:="large"
                            class="mx-1"
                            type="warning"
                            effect="dark"
                            round>
                        {{ scope.row.create_at }}
                    </el-tag>
                </div>
                <div v-if="scope.column.key == 'status'">
                    <el-switch
                               :loading="scope.row.switchLoading"
                               size="large"
                               v-model="scope.row.status"
                               active-value="1"
                               inactive-value="0"
                               class="ml-2"
                               @change="changeUserStatus(scope.row)"
                               inline-prompt
                               style="--el-switch-on-color: #077ed3; --el-switch-off-color: #ff4949"
                               active-text="启用"
                               inactive-text="禁用" />
                </div>
            </template>
        </myx-table>
        <!-- 分配角色弹框 -->
        <el-dialog width="30%" center v-model="showDialog" title="分配角色">
            <div class="select-user">
                <b>当前分配的用户:</b>
                <el-tag
                        type="danger"
                        size="large"
                        class="ml-2">
                    {{ targetUsername }}
                </el-tag>
            </div>
            <el-select v-model="selectRoleid" placeholder="选择角色">
                <el-option

                           v-for="item in roleOptions"
                           :key="item.roleid"
                           :label="item.roleName"
                           :value="item.roleid"
                           :disabled="item.disabled" />
            </el-select>

            <template #footer>
                <el-button type="primary" @click="handleAssignmentConfirm">确定</el-button>
                <el-button type="danger" @click="handleAssignmentCancel">取消</el-button>
            </template>
        </el-dialog>

        <myx-dialog  :formItems="formItem" :formData="formData" @ok="updateUser" v-model="showEditDialog"
                    :title="title" :reviewData="reviewData" :action="action"></myx-dialog>
    </div>
</template>
<script setup>
import { ElMessage, ElMessageBox } from "element-plus"
import isChild from "@/utils/isChild"
//引入roleStore
import useRole from "@/store/role"
//把用户的store引入
import useUser from "@/store/users"
//使用角色store
let roleStore = useRole()
//使用用户store
let userStore = useUser()
//定义弹框的表单数据
let formData = {
    useranme: "",
    password: "",
    nickname: "",
    phone: "",
    sex: ""

}
//定义弹框item
let formItem = [
    {
        key: "username",
        label: '用户名',
        prop: 'username',
        rules: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    },
    {
        key: "password",
        type: 'password',
        label: '新密码',
        prop: 'password'
    },
    {
        key: "nickname",
        label: '昵称',
        prop: 'nickname',
        rules: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
    },
    {
        key: 'phone',
        label: '手机号',
        prop: 'phone',
    },

    {
        key: 'sex',
        label: "性别",
        prop: "sex",
        rules: [{ required: true, message: '性别不能为空', trigger: 'blur' }]
    }
]
//定义表格data
let data = ref([])
//定义表格column
let column = ref([{
    key: "username",
    dataIndex: "username",
    label: "用户名",
    align: 'center',
    tableCell: true
},
{
    key: "nickname",
    dataIndex: "nickname",
    label: "昵称",
    align: 'center',
    tableCell: true
},
{
    key: "phone",
    dataIndex: "phone",
    label: "手机号",
    align: 'center',
    width: 150
},
{
    key: "roleName",
    dataIndex: "roleName",
    label: "角色名",
    align: 'center',
    tableCell: true
},
{
    key: "create_at",
    dataIndex: "create_at",
    label: "创建时间",
    align: 'center',
    tableCell: true
},
{
    key: 'sex',
    dataIndex: "sex",
    label: "性别",
    align: 'center',
    tableCell: true,
    width: 100
},
{
    key: "status",
    dataIndex: "status",
    label: "用户状态",
    align: 'center',
    tableCell: true,
    width: 100
},
{
    key: "action",
    label: "操作",
    align: 'center',
    tableCell: true,
    width: 400
}
])
//定义导出的表头数据
let titleList = [
    {
        key: 'username',
        title: '用户名'
    },
    {
        key: 'sex',
        title: '性别'
    }
]

//加载动画
let tableLoading = ref(false);

//分页
let pageSize = ref(6)
let currentPage = ref(1)
let pageTotal = ref(0)

//分页变化的时候的方法

let currentChange = (page) => {
    currentPage.value = page;
    getUsers()
}

//发起请求的方法
let getUsers = async () => {
    tableLoading.value = true
    let params = {
        page: currentPage.value,
        count: pageSize.value,
        order_by: -1
    }
    try {
        let res = await api.getUsersApi(params);
        tableLoading.value = false;
        res.data.forEach(item => {
            item.switchLoading = false
        })
        data.value = res.data;

        // console.log(res)
        pageTotal.value = res.total;
        setTimeout(() => {
            isInitialSwitch = false;
        })
    } catch (e) {

    }
}

//搜索的方法

let searchMethod = (key, currentPage, pageSize) => {
    // console.log(key)
    return api.getUsersApi({
        username: key,
        page: currentPage,
        count: pageSize
    })
}

//处理switch的事件在初始化的时候会执行一次的bug
let isInitialSwitch = true

//变更用户状态

let changeUserStatus = async (row) => {
    // console.log(row)
    //打开loading
    if (!isInitialSwitch) {
        row.switchLoading = true
        try {
            await api.updateUserApi({ unid: row.unid, status: row.status })
            row.switchLoading = false
            if (row.status === '1') {
                ElMessage.success(row.username + "用户已启用")
            } else {
                ElMessage.error(row.username + "用户已禁用")
            }

        } catch (e) {
            console.log(e)
            row.switchLoading = false;
            getUsers()
        }

    }
}

//声明角色选择的变量

let roleOptions = ref([])

//声明选中角色的v-model变量

let selectRoleid = ref("5")

//分配的用户名

let targetUsername = ref("")

//分配的用户unid

let unid = ref("");

//声明控制dialog打开和关闭的方法

let showDialog = ref(false)

//分配角色

let assignmentRole = async (row) => {
    //调用roleStore中方法,重新拉取所有的角色
    roleStore.getAllRoles();
    // console.log(roleStore.allRoles)
    // console.log(row)

    //修改展示的用户名信息

    targetUsername.value = row.nickname

    unid.value = row.unid;

    //开始处理数据,对于没有权限分配的选项我们要添加disabled属性
    roleOptions.value = roleStore.allRoles.map(role => {
        //这步的目的是为了不去修改store中的原始对象,以免对其它的数据造成影响
        let roleObj = {}
        //获取当前登入用户的角色id
        // console.log(userStore.userInfo.roleid)
        let currentRoleid = userStore.userInfo.roleid;
        // console.log('-----226',currentRoleid)
        // console.log('------227',role.roleid)
        //对比 哪些角色是当前角色自己角色,因为只能分配自己角色
        let flag = isChild(currentRoleid, role.roleid, roleStore.allRoles);
        // console.log(flag)

        roleObj = { ...role }

        if (!flag) {
            //不是自己的子级,添加disabled禁用
            roleObj.disabled = true;
        }

        return roleObj
    }).sort((a, b) => {
        if (a.disabled && !b.disabled) {
            return -1
        }
    })
    //控制dialog打开
    showDialog.value = true
}


//分配角色的dialog弹窗点取消按钮或者确定按钮的方法

let handleAssignmentConfirm = async () => {
    try {
        await api.assignmentRoleApi({ unid: unid.value, roleid: selectRoleid.value })
        let msg = `给${targetUsername.value}分配角色成功`
        ElMessage.success(msg)
        //更新列表
        getUsers()
    } catch (e) {
        console.log(e)
        ElMessage.error("分配角色失败:" + e.toString())
    }
    showDialog.value = false;
}

let handleAssignmentCancel = () => {
    showDialog.value = false
}


//打开弹窗
let reviewData = ref({}) //回显的数据
let openEditDialog = (row) => {
    showEditDialog.value = true
    reviewData.value = row;
    action.value = 'edit'
    title.value = '编辑用户'
    // console.log(row)
}

//用户编辑模块

let showEditDialog = ref(false)


//添加用户
let title = ref('添加用户')

let addUser = async () => {
    action.value = 'add'
    title.value = '添加用户'
    showEditDialog.value = true;
}


//删除用户

let deleteUser = (row) => {
    // console.log(row)
    ElMessageBox.confirm(h('p', [
        h('span', '此操作将永久删除 '),
        h('span', { style: 'color:red;font-size:18px' }, row.username),
        h('span', ' 用户, 是否继续?')
    ]), '⚠️警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true;
                instance.confirmButtonText = '正在删除...';
                try {
                    await api.deleteUserApi({ unid: row.unid })
                    ElMessage.success("删除用户成功")
                    getUsers()
                    done()
                } catch (e) {
                    ElMessage.error("删除用户失败:" + e.toString())
                    done()
                }
            } else {
                done();
            }
        }
    })
}

//点击确定后更新信息

let action = ref("edit")

let updateUser = async (newData) => {
    if (action.value == 'edit') {
        console.log(newData)
        let data = {...newData}
        // delete data.unid
        delete data.roleid
        try {
            await api.updateUserApi(data);
            ElMessage.success("更新用户信息成功")
            //更新列表
            getUsers()
        } catch (e) {
            ElMessage.error("更新用户信息失败:" + e.toString())
        }
    } else if (action.value = 'add') {
        try {
            await api.addUserApi(newData);
            getUsers()//更新列表
            ElMessage.success("添加用户信息成功")
        } catch (e) {
            ElMessage.error("添加用户信息失败:" + e.toString())
        }
    }
}



onMounted(() => {
    getUsers()
})
</script>
<style scoped>
.users :deep(.el-dialog__body) {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.select-user {
    margin: 20px;
    font-size: 18px;
}

.select-user .el-tag {
    font-size: 18px;
    margin-left: 10px;
}

@keyframes changeImg {
    from {
        left: -20%;
    }

    100% {
        left: 120%;
    }
}

.twink {
    overflow: hidden;
    position: relative;
}

.twink::after {
    position: absolute;
    animation: changeImg 3s ease 0s infinite;
    top: 0;
    width: 20%;
    height: 100%;
    content: "";
    background: linear-gradient(to right, rgba(216, 204, 204, 0) 0, rgba(255, 255, 255, 0.905) 50%, rgba(255, 255, 255, 0) 100%);
    transform: skewX(-45deg);
    animation-iteration-count: infinite;
}
</style>